import 'package:flutter_enjoy_plus/constants/index.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TokenManager {
  // 定义一个token变量
  String _token = '';
  String _refreshToken = '';
  // 初始化首选项实例
  Future<SharedPreferences> _getInstance() {
    return SharedPreferences.getInstance();
  }

  // 项目启动时初始化
  init() async {
    // 获取首选项实例
    final instance = await _getInstance();
    _token = instance.getString(GlobalVariable.TOKEN_KEY) ?? '';
    _refreshToken = instance.getString('GlobalVariable.RERRESH_TOKEN_KEY') ?? '';
  }

  // 存储token
  setToken(String token, {String? refreshToken}) async {
    // 获取首选项实例
    final instance = await _getInstance();
    // 基于实例 存储
    instance.setString(GlobalVariable.TOKEN_KEY, token);
    // 更新token
    _token = token;
    if (refreshToken != null) {
      instance.setString('GlobalVariable.RERRESH_TOKEN_KEY', refreshToken);
      // 更新token
      _refreshToken = refreshToken;
    }
  }

  // 获取token
  getToken() {
    return _token ?? '';
  }

  // 获取refreshToken
  getRefreshToken() {
    return _refreshToken ?? '';
  }

  // 删除token
  deleteToken() async {
    // 获取首选项实例
    final instance = await _getInstance();
    instance.remove(GlobalVariable.TOKEN_KEY);
    // 清除token
    _token = '';

    instance.remove('GlobalVariable.RERRESH_TOKEN_KEY');
    // 清除refreshToken
    _refreshToken = '';
  }
}

final tokenManager = TokenManager();
